var Workport = Workport || {};
//@Path("/Tag")
Workport.ContactAPI = (function(){
	
	var root = WP_RESTFUL_URL + (WP_RESTFUL_URL.endsWith('/') ? '' : '/') + 'Contact';
	
	var urls = ["","/Self","/New"];
	
	function getUrl(/*index, replace1, replace2, ...*/) {
		var index, i, loops, r;
		loops = arguments.length;
		if (loops > 0) {
			index = arguments[0];
			r = root + urls[index];
			for (i = 1; i < loops; i++)
				r = r.replace("{"+i+"}", arguments[i]);
		}
		return r;
	}
	
	function sendGetRequest(url,callback,query,sync){
		if(sync){
			return sfw.Http.syncGet(url,callback,query);
		} else {
			return sfw.Http.get(url,callback,query);
		}
	}
	
	return {
		// @GET		@Path("/")
		// Contact?userIdkey=CA228&userNamekey=CA228&locationKey=&positionKey=&action=3&ps=20&offset=0 
		// public ContactResponse GetAllContacts()
		searchContact:function(handler,request){
			var domain = {
				
				ps : request.pageSize,
				offset : request.offset
			}
			if(request.userId || request.userName || request.location || request.position){
				domain.userIdkey = request.userId;
				domain.userNamekey = request.userName;
				domain.locationKey = request.location;
				domain.positionKey = request.position;
				domain.action = request.action;
			}
			return sendGetRequest(getUrl(0),function(xhr,data){
				if (!sfw.Http.handleError(xhr, data)) {
					if(jQuery.isFunction(handler)){
						handler(data, xhr);
					}
				}
			}, domain ,request.sync);
		},
		// @GET		@Path("/Self")
		// public ContactResponse GetMyContacts()
		getSelfContact:function(handler,request){
			var domain = {
				filter:request.filter,
				ps:request.pageSize,
				offset:request.offset
			};
			if(request.action || request.userName){
				domain.action = request.action;
				domain.userNamekey = request.userName;
			}
			if(request.userId){
				domain.userIdkey = request.userId;
			}
			if(request.position){
				domain.positionKey = request.position;
			}
			return sendGetRequest(getUrl(1),function(xhr,data){
				if (!sfw.Http.handleError(xhr, data)) {
					if(jQuery.isFunction(handler)){
						handler(data,xhr);
					}
				}
			},domain,request.sync);
		},
		// @POST		@Path("/New")
		// public BasicResponse NewContacts()
		addContact:function(handler,request){
			return sfw.Http.post(getUrl(2),function(xhr,data){
				if (!sfw.Http.handleError(xhr, data)) {
					if(jQuery.isFunction(handler)){
						handler(data, xhr);
					}
				}
			},null,{
				IDs:request.ids,
				action:request.action
			});
		}
	}
})();
